import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import User from '../components/user/User.vue'
import Rights from '../components/power/Rights.vue'
import Role from '../components/power/Role.vue'
import Cate from '../components/goods/Cate.vue'
import Params from '../components/goods/Params.vue'
import GoodsList from '../components/goods/List.vue'
import Add from '../components/goods/Add.vue'
import Order from '../components/order/Order.vue'
import Report from '../components/report/Report.vue'


Vue.use(VueRouter)

const routes = [{
        // 当访问路径是 '/', 就自动重定向到 '/login'页面
        path: '/',
        redirect: '/login'
    },
    {
        // login 路由
        path: '/login',
        component: Login
    },
    {
        // 首页home路由
        path: '/home',
        // 当访问home路由时重定向到welcome路由
        redirect: '/welcome',
        component: Home,
        children: [{
                path: '/welcome',
                component: Welcome
            },
            {
                path: '/users',
                component: User
            },
            {
                path: '/rights',
                component: Rights
            },
            {
                path: '/roles',
                component: Role
            },
            {
                path: '/categories',
                component: Cate
            },
            {
                path: '/params',
                component: Params
            },
            {
                path: '/goods',
                component: GoodsList,
            },
            {
                path: '/goods/add',
                component: Add
            },
            {
                path: '/orders',
                component: Order
            },
            {
                path: '/reports',
                component: Report
            }

        ]
    }
]

const router = new VueRouter({
    routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
    // to 将要访问的路径
    // from 从哪个路径跳转而来
    // next 是一个函数，表示放行
    // next() 直接放行或者 next('/login') 强制跳转至登录页面

    // 首先判断用户访问的页面是否是登录页面，如果是的话则直接就放行，不是的话则验证token，如果可以从sessionStorage中取到token，则放行，否则直接强制跳转至login页面

    if (to.path === '/login') return next()
        // 获取sessionStorage里面的token
    const token = window.sessionStorage.getItem('token')
    if (!token) return next('/login')
    next()
})

export default router